package cn.yi.fast.security.shiro;

import cn.yi.fast.security.domain.User;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

public class UserCredentialsMatcher extends SimpleCredentialsMatcher {

    private Cache<String, AtomicInteger> passwordRetryCache;

    /**
     * 默认重试次数
     */
    @Setter
    private Long retryTimes = 20L;

    public UserCredentialsMatcher(CacheManager cacheManager, String cacheName) {
        passwordRetryCache = cacheManager.getCache(cacheName);
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        User user = (User) token.getPrincipal();
        String username = user.getUsername();
        AtomicInteger userAtomicInteger = passwordRetryCache.get(username);
        if (Objects.isNull(userAtomicInteger)) {
            userAtomicInteger = new AtomicInteger(0);
            passwordRetryCache.put(username,userAtomicInteger);
        }
        if (userAtomicInteger.getAndIncrement() > retryTimes) {
            throw new ExcessiveAttemptsException("超过最大的登陆次数,稍后再试");
        }
        UsernamePasswordToken passwordToken = (UsernamePasswordToken) token;

        Object password = ShiroUtils.sha256(String.valueOf(passwordToken.getPassword()), user.getSalt());

        Object accountCredentials = getCredentials(info);

        boolean matchs = Objects.equals(password,accountCredentials);
        if(matchs){
            passwordRetryCache.remove(username);
        }else{
            passwordRetryCache.put(username,userAtomicInteger);
        }
        return matchs;
    }
}
